package com.zyd.util;

import com.google.common.base.Strings;
import com.zyd.constants.ErrorDef;
import com.zyd.exception.BusinessException;
import org.omg.CORBA.SystemException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidationUtil {

    public static boolean isPhoneNumber(String phoneNo) {
        if (Strings.isNullOrEmpty(phoneNo)) {
            return false;
        }
        if (phoneNo.length() == 11) {
            for (int i = 0; i < 11; i++) {
                if (!Character.isDigit(phoneNo.charAt(i))) {
                    return false;
                }
            }
            Pattern p = Pattern.compile("^(0|86|17951)?(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[57]|19[0-9]|16[0-9])[0-9]{8}$");
            Matcher m = p.matcher(phoneNo);
            return m.matches();
        }
        else {
            Pattern p1 = Pattern.compile("(^(0\\d{2})-(\\d{8})$)|(^(0\\d{3})-(\\d{8})$)|(^(0\\d{2})-(\\d{7})-(\\d+)$)|(^(0\\d{3})-(\\d{7})-(\\d+)$)");
            Matcher m1 = p1.matcher(phoneNo);
            return m1.matches();
        }
    }
    public void checkPhoneNumber(String phone) {
        if (!isPhoneNumber(phone)) {
            throw new BusinessException(ErrorDef.SYSTEM_ERROR, "手机号格式不正确");
        }
    }

    public void checkIdCard(String phone) {
        if (!isIdCard(phone)) {
            throw new BusinessException(ErrorDef.SYSTEM_ERROR, "身份证号格式不正确");
        }
    }

    public static boolean isIdCard(String no)
    {
        // 对身份证号进行长度等简单判断
        if (no == null || no.length() != 18 || !no.matches("\\d{17}[0-9X]"))
        {
            return false;
        }
        // 1-17位相乘因子数组
        int[] factor = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
        // 18位随机码数组
        char[] random = "10X98765432".toCharArray();
        // 计算1-17位与相应因子乘积之和
        int total = 0;
        for (int i = 0; i < 17; i++)
        {
            total += Character.getNumericValue(no.charAt(i)) * factor[i];
        }
        // 判断随机码是否相等
        return random[total % 11] == no.charAt(17);
    }



}
